﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Text;
using System.EnterpriseServices;
using System.Configuration;
using Models;
using Common;
using Langben.DAL;
using Langben.BLL;
using Langben.App.Models;
using System.Collections;
using System.Transactions;
using System.Data;

namespace Langben.App.Controllers
{
    /// <summary>
    /// 移库
    /// </summary>
    public class ts_billmoveController : BaseController
    {

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Index()
        {
        
            return View();
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult YKMXForm()
        { 
            return View();
        }
               
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult LLHZBForm()
        { 
            return View();
        }

        
         /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public ActionResult IndexSef()
        {

            return View();
        }
        /// <summary>
        /// 异步加载数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetData(string id, int page, int rows, string order, string sort, string search)
        {
            DateTime dtStart = Convert.ToDateTime("1900-10-10");
            DateTime dtEnd = DateTime.Now;
            string DH = "";
            string YSDH = "";

            if (search != null)
            {
                string[] searchStr = search.Split('^');
                if (searchStr[0].Split('&')[1].ToString() != "")
                {
                    dtStart = Convert.ToDateTime(searchStr[0].Split('&')[1]);
                }
                if (searchStr[1].Split('&')[1].ToString() != "")
                {
                    dtEnd = Convert.ToDateTime(searchStr[1].Split('&')[1]);
                }
                if (searchStr[2].Split('&')[1].ToString() != "")
                {
                    DH = searchStr[2].Split('&')[1];
                }
                if (searchStr[3].Split('&')[1].ToString() != "")
                {
                    YSDH = searchStr[3].Split('&')[1];
                }

            }


            Hashtable ht = new Hashtable();
            SqlReadXml rx = new SqlReadXml();
            ht.Add("@c_type", "移库");
            ht.Add("@DTStart", dtStart);
            ht.Add("@DTEnd", dtEnd);
            string sqlString = rx.SqlBack("sel_YKGL");
            string strwhere = "";
            if (DH != "")
            {
                strwhere += " and convert(varchar(20),i_no) like '%'+'" + DH + "'+'%' ";
            }
            if (YSDH != "")
            {
                strwhere += " and c_orgno like '%'+'" + YSDH + "'+'%' ";
            }

            sqlString = sqlString.Replace("@CC", strwhere);
            DataSet ds = rx.DsDoSQL(sqlString, ht);
            List<ts_billmove> billmoveList = new List<ts_billmove>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                //c_type,i_no,dt_dt,c_base,c_id,c_orgno,c_agency,c_keeper,c_clerk,c_audi,c_comment,i_sign

                ts_billmove billmove = new ts_billmove();
                billmove.c_type = dr["c_type"].ToString();
                billmove.Id = dr["Id"].ToString();
                billmove.dt_dt = Convert.ToDateTime(dr["dt_dt"].ToString());
                billmove.c_base1 = dr["c_base1"].ToString();
                billmove.c_base2 = dr["c_base2"].ToString(); 
                billmove.i_no = Convert.ToInt32(dr["i_no"].ToString());
                billmove.c_orgno = dr["c_orgno"].ToString();
                billmove.c_keeper1 = dr["c_keeper1"].ToString();
                billmove.c_keeper2 = dr["c_keeper2"].ToString();
                billmove.c_clerk = dr["c_clerk"].ToString();
                billmove.c_audi = dr["c_audi"].ToString();
                billmove.c_comment = dr["c_comment"].ToString();
                billmove.i_sign = dr["i_sign"].ToString();
                billmoveList.Add(billmove);
            } 
            return Json(new datagrid
            {
                total = billmoveList.Count(),
                rows = billmoveList.Select(s => new
                {
                    Id = s.Id
					,c_type = s.c_type
					,i_no = s.i_no
					,dt_dt = s.dt_dt
					,c_base1 = s.c_base1
					,c_base2 = s.c_base2
					,c_orgno = s.c_orgno
					,c_keeper1 = s.c_keeper1
					,c_keeper2 = s.c_keeper2
					,c_clerk = s.c_clerk
					,c_audi = s.c_audi
					,c_comment = s.c_comment
					,i_sign = s.i_sign
					
                }

                    )
            });
        }


        [HttpPost]
        public JsonResult PrintRK(string search)
        {
            ts_billmove billmove = m_BLL.GetById(search);
            var queryData = new BLL.ts_billmovedetailBLL().GetAll().Where(o => o.i_no == search);
            //为打印提供html相关超文本内容。 
            StringBuilder sb = new StringBuilder();
            sb.Append("<table style='width:100%;font-size:12px;'><tr><td width='25%' align='left'>移出仓库：" + billmove.c_base1 + "</td><td width='25%' align='left'>保管员：" + billmove.c_keeper1 + "</td><td width='25%' align='left'>移入仓库：" + billmove.c_base2 + "</td><td width='25%' align='left'>保管员：" + billmove.c_keeper2 + "</td></tr>");
            sb.Append("<tr><td colspan='4'>备注："+billmove.c_comment+"</td></tr></table>");
            sb.Append("<table border=1 cellSpacing=0 cellPadding=1 width=\"100%\" style=\"border-collapse:collapse;font-size:12px;line-height:30px\"  bordercolor=\"#333333\"> ");
            sb.Append("<thead><tr>");
            sb.Append("<td><div align=\"center\">物料编码</div></td>");
            sb.Append("<TD><div align=\"center\">品名</div></TD>");
            sb.Append("<TD><div align=\"center\">规格</div></TD>");
            sb.Append("<TD><div align=\"center\">单位</div></TD>");
            sb.Append("<TD><div align=\"center\">单价</div></TD>");
            sb.Append("<TD><div align=\"center\">数量</div></TD>");
            sb.Append("<TD><div align=\"center\">金额</div></TD>");
            sb.Append("<TD><div align=\"center\">备注</div></TD>");
            sb.Append("</TR>");
            sb.Append("</thead>");
            sb.Append("<tbody>");
            double allamount = 0;
            foreach (var item in queryData)
            {
                ts_goods goods = new BLL.ts_goodsBLL().GetAll().Where(o => o.c_code == item.c_code).First();
                sb.Append("<tr>");
                sb.Append("<td>");
                sb.Append(item.c_code);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(goods.c_desc);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(goods.c_model);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(goods.c_unit);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.f_price);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.f_quant);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.f_amount);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.c_comment);
                sb.Append("</td>");

                sb.Append("</tr>");
                allamount += Convert.ToDouble(item.f_amount);
            }
            sb.Append("<tr>");
            sb.Append("<td colspan='8'><b>");
            sb.Append("&nbsp;&nbsp;&nbsp;&nbsp;合计(大写)：&nbsp;" + ToCHNMoney.DoubleToCHNMoney(allamount) + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;￥" + allamount);
            sb.Append("</td>");

            sb.Append("</b></tr>");
            sb.Append("</tbody>");
            sb.Append("</TABLE>");

            return Json(new { success = true, data = sb.ToString() }, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 异步加载数据入库退货明细单中的汇总
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetYKData(string search)
        { 
            DateTime dtStart = Convert.ToDateTime("1900-10-10");
            DateTime dtEnd = DateTime.Now;
            string DH = "";
            string YSDH = "";

            if (search != null)
            {
                string[] searchStr = search.Split('^');
                if (searchStr[0].Split('&')[1].ToString() != "")
                {
                    dtStart = Convert.ToDateTime(searchStr[0].Split('&')[1]);
                }
                if (searchStr[1].Split('&')[1].ToString() != "")
                {
                    dtEnd = Convert.ToDateTime(searchStr[1].Split('&')[1]);
                }
                if (searchStr[2].Split('&')[1].ToString() != "")
                {
                    DH = searchStr[2].Split('&')[1];
                }
                if (searchStr[3].Split('&')[1].ToString() != "")
                {
                    YSDH = searchStr[3].Split('&')[1];
                }
            }

            Hashtable ht = new Hashtable();
            SqlReadXml rx = new SqlReadXml();
            ht.Add("@DTStart", dtStart);
            ht.Add("@DTEnd", dtEnd);
            string sqlString = rx.SqlBack("sel_YKMX");
            string strwhere = "";
            if (DH != "")
            {
                strwhere += " and convert(varchar(20),ts_billmove.i_no) like '%'+'" + DH + "'+'%' ";
            }
            if (YSDH != "")
            {
                strwhere += " and c_orgno like '%'+'" + YSDH + "'+'%' ";
            }

            sqlString = sqlString.Replace("@CC", strwhere);
            DataSet ds = rx.DsDoSQL(sqlString, ht);
            List<ts_billmove> billmoveList = new List<ts_billmove>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ts_billmove billmove = new ts_billmove();
                billmove.c_code = dr["c_code"].ToString();
                billmove.c_desc = dr["c_desc"].ToString();
                billmove.c_model = dr["c_model"].ToString();
                billmove.c_unit = dr["c_unit"].ToString();
                billmove.allquant = dr["allquant"].ToString();
                billmove.allamount = dr["allamount"].ToString();
                billmoveList.Add(billmove);
            }

            return Json(new datagrid
            {
                total = billmoveList.Count(),
                rows = billmoveList.Select(s => new
                {
                    c_code = s.c_code
                    ,
                    c_desc = s.c_desc
                    ,
                    c_model = s.c_model
                    ,
                    c_unit = s.c_unit
                    ,
                    allquant = s.allquant
                    ,
                    allamount = s.allamount

                }

                    )
            });
        }



        [HttpPost]
        public JsonResult PrintYK(string search)
        {
            DateTime dtStart = Convert.ToDateTime("1900-10-10");
            DateTime dtEnd = DateTime.Now;
            string DH = "";
            string YSDH = "";

            if (search != "")
            {
                string[] searchStr = search.Split('^');
                if (searchStr[0].Split('&')[1].ToString() != "")
                {
                    dtStart = Convert.ToDateTime(searchStr[0].Split('&')[1]);
                }
                if (searchStr[1].Split('&')[1].ToString() != "")
                {
                    dtEnd = Convert.ToDateTime(searchStr[1].Split('&')[1]);
                }
                if (searchStr[2].Split('&')[1].ToString() != "")
                {
                    DH = searchStr[2].Split('&')[1];
                }
                if (searchStr[3].Split('&')[1].ToString() != "")
                {
                    YSDH = searchStr[3].Split('&')[1];
                }
            }

            Hashtable ht = new Hashtable();
            SqlReadXml rx = new SqlReadXml();
            ht.Add("@DTStart", dtStart);
            ht.Add("@DTEnd", dtEnd);
            string sqlString = rx.SqlBack("sel_YKMX");
            string strwhere = "";
            if (DH != "")
            {
                strwhere += " and convert(varchar(20),ts_billmove.i_no) like '%'+'" + DH + "'+'%' ";
            }
            if (YSDH != "")
            {
                strwhere += " and c_orgno like '%'+'" + YSDH + "'+'%' ";
            }

            sqlString = sqlString.Replace("@CC", strwhere);
            DataSet ds = rx.DsDoSQL(sqlString, ht);
            List<ts_billmove> billmoveList = new List<ts_billmove>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ts_billmove billmove = new ts_billmove();
                billmove.c_code = dr["c_code"].ToString();
                billmove.c_desc = dr["c_desc"].ToString();
                billmove.c_model = dr["c_model"].ToString();
                billmove.c_unit = dr["c_unit"].ToString();
                billmove.allquant = dr["allquant"].ToString();
                billmove.allamount = dr["allamount"].ToString();
                billmoveList.Add(billmove);
            }

            //为打印提供html相关超文本内容。 
            StringBuilder sb = new StringBuilder();
            sb.Append("<table border=1 cellSpacing=0 cellPadding=1 width=\"100%\" style=\"border-collapse:collapse;font-size:12px;line-height:30px\"  bordercolor=\"#333333\"> ");
            sb.Append("<thead><tr>");
            sb.Append("<td><div align=\"center\">编号</div></td>");
            sb.Append("<TD><div align=\"center\">品名</div></TD>");
            sb.Append("<TD><div align=\"center\">规格</div></TD>");
            sb.Append("<TD><div align=\"center\">单位</div></TD>");
            sb.Append("<TD><div align=\"center\">数量</div></TD>");
            sb.Append("<TD><div align=\"center\">金额</div></TD>");
            sb.Append("</TR>");
            sb.Append("</thead>");
            sb.Append("<tbody>");


            double allMoney = 0;
            foreach (ts_billmove item in billmoveList)
            {
                sb.Append("<tr>");
                sb.Append("<td>");
                sb.Append(item.c_code);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.c_desc);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.c_model);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.c_unit);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.allquant);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.allamount);
                sb.Append("</td>");

                sb.Append("</tr>");
                allMoney += Convert.ToDouble(item.allamount);
            }
            sb.Append("<tr>");
            sb.Append("<td colspan='6'><b>");
            sb.Append("<div  style='float:left;width:20%' align='right'>&nbsp;合计：&nbsp;</div><div style='float:right;width:79%' align='right'>" + allMoney + "</div>");
            sb.Append("</td>");
            sb.Append("</b></tr>");
            sb.Append("</tbody>");
            sb.Append("</TABLE>");

            return Json(new { success = true, data = sb.ToString() }, JsonRequestBehavior.AllowGet);
        }

         
        /// <summary>
        /// 异步加载数据入库退货明细单中的明细
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetYKData2(string search)
        {
            DateTime dtStart = Convert.ToDateTime("1900-10-10");
            DateTime dtEnd = DateTime.Now;
            string DH = "";
            string YSDH = "";

            if (search != null)
            {
                string[] searchStr = search.Split('^');
                if (searchStr[0].Split('&')[1].ToString() != "")
                {
                    dtStart = Convert.ToDateTime(searchStr[0].Split('&')[1]);
                }
                if (searchStr[1].Split('&')[1].ToString() != "")
                {
                    dtEnd = Convert.ToDateTime(searchStr[1].Split('&')[1]);
                }
                if (searchStr[2].Split('&')[1].ToString() != "")
                {
                    DH = searchStr[2].Split('&')[1];
                }
                if (searchStr[3].Split('&')[1].ToString() != "")
                {
                    YSDH = searchStr[3].Split('&')[1];
                }

            }


            Hashtable ht = new Hashtable();
            SqlReadXml rx = new SqlReadXml();
            ht.Add("@DTStart", dtStart);
            ht.Add("@DTEnd", dtEnd);
            string sqlString = rx.SqlBack("sel_YKMX2");
            string strwhere = "";
            if (DH != "")
            {
                strwhere += " and convert(varchar(20),ts_billmove.i_no) like '%'+'" + DH + "'+'%' ";
            }
            if (YSDH != "")
            {
                strwhere += " and c_orgno like '%'+'" + YSDH + "'+'%' ";
            }

            sqlString = sqlString.Replace("@CC", strwhere);
            DataSet ds = rx.DsDoSQL(sqlString, ht);
            List<ts_billmove> billmoveList = new List<ts_billmove>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ts_billmove billmove = new ts_billmove();
                billmove.c_type = dr["c_type"].ToString();
                billmove.i_no = Convert.ToInt32(dr["i_no"].ToString());
                billmove.dt_dt = Convert.ToDateTime(dr["dt_dt"].ToString());
                billmove.c_base1 = dr["c_base1"].ToString();
                billmove.c_base2 = dr["c_base2"].ToString(); 
                billmove.c_code = dr["c_code"].ToString();
                billmove.c_desc = dr["c_desc"].ToString();
                billmove.c_model = dr["c_model"].ToString();
                billmove.c_unit = dr["c_unit"].ToString();
                billmove.allquant = dr["allquant"].ToString();
                billmove.allamount = dr["allamount"].ToString();
                billmove.f_price = dr["f_price"].ToString();
                billmove.c_comment = dr["c_comment"].ToString();
                billmoveList.Add(billmove);
            }


            return Json(new datagrid
            {
                total = billmoveList.Count(),
                rows = billmoveList.Select(s => new
                {
                    c_type = s.c_type
                    ,
                    i_no = s.i_no
                    ,
                    dt_dt = s.dt_dt
                    ,
                    c_base1 = s.c_base1
                    ,
                    c_base2=s.c_base2
                    , 
                    c_code = s.c_code
                    ,
                    c_desc = s.c_desc
                    ,
                    c_model = s.c_model
                    ,
                    c_unit = s.c_unit
                    ,
                    allquant = s.allquant
                    ,
                    allamount = s.allamount
                    ,
                    f_price = s.f_price
                    ,
                    c_comment = s.c_comment

                }

                    )
            });
        }

        [HttpPost]
        public JsonResult PrintYK2(string search)
        {
            DateTime dtStart = Convert.ToDateTime("1900-10-10");
            DateTime dtEnd = DateTime.Now;
            string DH = "";
            string YSDH = "";

            if (search != "")
            {
                string[] searchStr = search.Split('^');
                if (searchStr[0].Split('&')[1].ToString() != "")
                {
                    dtStart = Convert.ToDateTime(searchStr[0].Split('&')[1]);
                }
                if (searchStr[1].Split('&')[1].ToString() != "")
                {
                    dtEnd = Convert.ToDateTime(searchStr[1].Split('&')[1]);
                }
                if (searchStr[2].Split('&')[1].ToString() != "")
                {
                    DH = searchStr[2].Split('&')[1];
                }
                if (searchStr[3].Split('&')[1].ToString() != "")
                {
                    YSDH = searchStr[3].Split('&')[1];
                }

            }


            Hashtable ht = new Hashtable();
            SqlReadXml rx = new SqlReadXml();
            ht.Add("@DTStart", dtStart);
            ht.Add("@DTEnd", dtEnd);
            string sqlString = rx.SqlBack("sel_YKMX2");
            string strwhere = "";
            if (DH != "")
            {
                strwhere += " and convert(varchar(20),ts_billmove.i_no) like '%'+'" + DH + "'+'%' ";
            }
            if (YSDH != "")
            {
                strwhere += " and c_orgno like '%'+'" + YSDH + "'+'%' ";
            }

            sqlString = sqlString.Replace("@CC", strwhere);
            DataSet ds = rx.DsDoSQL(sqlString, ht);
            List<ts_billmove> billmoveList = new List<ts_billmove>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ts_billmove billmove = new ts_billmove();
                billmove.c_type = dr["c_type"].ToString();
                billmove.i_no = Convert.ToInt32(dr["i_no"].ToString());
                billmove.dt_dt = Convert.ToDateTime(dr["dt_dt"].ToString());
                billmove.c_base1 = dr["c_base1"].ToString();
                billmove.c_base2 = dr["c_base2"].ToString();
                billmove.c_code = dr["c_code"].ToString();
                billmove.c_desc = dr["c_desc"].ToString();
                billmove.c_model = dr["c_model"].ToString();
                billmove.c_unit = dr["c_unit"].ToString();
                billmove.allquant = dr["allquant"].ToString();
                billmove.allamount = dr["allamount"].ToString();
                billmove.f_price = dr["f_price"].ToString();
                billmove.c_comment = dr["c_comment"].ToString();
                billmoveList.Add(billmove);
            }


            //为打印提供html相关超文本内容。 
            StringBuilder sb = new StringBuilder();
            sb.Append("<table border=1 cellSpacing=0 cellPadding=1 width=\"100%\" style=\"border-collapse:collapse;font-size:12px;line-height:30px\"  bordercolor=\"#333333\"> ");
            sb.Append("<thead><tr>");
            sb.Append("<td><div align=\"center\">类型</div></td>");
            sb.Append("<TD><div align=\"center\">单号</div></TD>");
            sb.Append("<TD><div align=\"center\">日期</div></TD>");
            sb.Append("<TD><div align=\"center\">移出库</div></TD>");
            sb.Append("<TD><div align=\"center\">移入库</div></TD>"); 
            sb.Append("<TD><div align=\"center\">编号</div></TD>");
            sb.Append("<TD><div align=\"center\">品名</div></TD>");
            sb.Append("<TD><div align=\"center\">规格</div></TD>");
            sb.Append("<TD><div align=\"center\">单位</div></TD>");
            sb.Append("<TD><div align=\"center\">数量</div></TD>");
            sb.Append("<TD><div align=\"center\">单价</div></TD>");
            sb.Append("<TD><div align=\"center\">金额</div></TD>");
            sb.Append("<TD><div align=\"center\">备注</div></TD>");
            sb.Append("</TR>");
            sb.Append("</thead>");
            sb.Append("<tbody>");


            double allMoney = 0;
            foreach (ts_billmove item in billmoveList)
            {
                sb.Append("<tr>");
                sb.Append("<td>");
                sb.Append(item.c_type);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.i_no);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.dt_dt);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.c_base1);
                sb.Append("</td>");
                 
                sb.Append("<td>");
                sb.Append(item.c_base2);
                sb.Append("</td>");
        
                sb.Append("<td>");
                sb.Append(item.c_code);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.c_desc);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.c_model);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.c_unit);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.allquant);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.f_price);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.allamount);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.c_comment);
                sb.Append("</td>");

                sb.Append("</tr>");
                allMoney += Convert.ToDouble(item.allamount);
            }
            sb.Append("<tr>");
            sb.Append("<td colspan='14'><b>");
            sb.Append("<div style='float:left;width:20%' align='right'>&nbsp;合计：&nbsp;</div><div style='float:right;width:79%'  align='right'>" + allMoney + "</div>");
            sb.Append("</td>");
            sb.Append("</b></tr>");
            sb.Append("</tbody>");
            sb.Append("</TABLE>");

            return Json(new { success = true, data = sb.ToString() }, JsonRequestBehavior.AllowGet);
        } 



        /// <summary>
        /// 查看详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [SupportFilter]  
        public ActionResult Details(string id)
        {
            ts_billmove item = m_BLL.GetById(id);
            return View(item);

        }
 
        /// <summary>
        /// 首次创建
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Create(string id)
        {
            if (m_BLL.GetAll().Where(o => o.c_type == "移库").Count() > 0)
            {
                ViewData["DH"] = m_BLL.GetAll().Where(o => o.c_type == "移库").OrderByDescending(o => o.i_no).First().i_no + 1;
            }
            else
            {
                ViewData["DH"] = 1;
            }
            ViewData["person"] = GetCurrentPerson();
            return View();
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Create(ts_billmove entity)
        {
            using (TransactionScope transactionScope = new TransactionScope())
            {
                try
                {
                    //if (entity != null && ModelState.IsValid)
                    //{
                    string currentPerson = GetCurrentPerson();
                    //entity.CreateTime = DateTime.Now;
                    //entity.CreatePerson = currentPerson;

                    entity.Id = Result.GetNewId();
                    entity.c_type = "移库";
                    string returnValue = string.Empty;
                    if (m_BLL.Create(ref validationErrors, entity))
                    {
                        //LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + "，入库表的信息的Id为" + entity.Id, "入库表"
                        //    );//写入日志 
                        //return Json(Suggestion.InsertSucceed);
                    }
                    else
                    {
                        if (validationErrors != null && validationErrors.Count > 0)
                        {
                            validationErrors.All(a =>
                            {
                                returnValue += a.ErrorMessage;
                                return true;
                            });
                        }
                        LogClassModels.WriteServiceLog(Suggestion.InsertFail + "，移库表的信息，" + returnValue, "移库表"
                            );//写入日志                      
                        return Json(Suggestion.InsertFail + returnValue); //提示插入失败
                    }

                    if (entity.GoodsDetail != null)
                    {
                        string[] rowsInf = entity.GoodsDetail.Split('^');

                        for (int i = 0; i < rowsInf.Length - 1; i++)
                        {
                            string aaad = rowsInf[i];
                            object arrayObj;
                            arrayObj = new Hashtable();
                            arrayObj = JSON.JsonDecode(rowsInf[i]);
                            Hashtable ht = (Hashtable)arrayObj;
                            Dictionary<string, string> dict = new Dictionary<string, string>();//Dictionary接受Json字符串
                            foreach (DictionaryEntry de in ht)
                            {
                                if (dict.ContainsKey(de.Key.ToString())) continue;//不能重复啊
                                dict.Add(de.Key.ToString(), de.Value == null ? "" : de.Value.ToString());
                            }

                            ts_billmovedetail billmovedetail = new ts_billmovedetail();
                            ts_billmovedetailBLL tbtb = new ts_billmovedetailBLL();
                            billmovedetail.Id = Result.GetNewId();
                            billmovedetail.c_type = "移库";
                            billmovedetail.i_no = entity.Id;
                            billmovedetail.i_num = i + 1;
                            billmovedetail.c_code = dict["c_code"].GetString();
                            billmovedetail.f_quant = Convert.ToDecimal(dict["f_quant"].GetString());
                            billmovedetail.f_price = StrToDecimal(dict["f_price"].GetString());
                            billmovedetail.f_amount = StrToDecimal(dict["f_quant"].GetString()) * StrToDecimal(dict["f_price"].GetString());
                            billmovedetail.c_comment = dict["c_comment"].GetString();

                            tbtb.Create(ref validationErrors, billmovedetail);

                        }
                        transactionScope.Complete();
                        LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + "，移库表的信息Id为" + entity.Id + "的商品信息", "移库商品表");//写入日志 
                        return Json(Suggestion.InsertSucceed);
                    }
                    transactionScope.Complete();
                    LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + "，移库表的信息Id为" + entity.Id, "移库表"
                           );//写入日志 
                    return Json(Suggestion.InsertSucceed);
                    //}
                }
                catch
                {
                    Transaction.Current.Rollback();
                }
            }

            return Json(Suggestion.InsertFail + "，请核对输入的数据的格式"); //提示输入的数据的格式不对 
        }



        //字符串类型转化为decimal类型
        protected decimal StrToDecimal(string str)
        {
            decimal queryvalue = 0;
            if (str != "")
            {
                queryvalue = Convert.ToDecimal(str);
            }
            return queryvalue;
        }



        /// <summary>
        /// 首次编辑
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns> 
        [SupportFilter] 
        public ActionResult Edit(string id)
        {
            ts_billmove item = m_BLL.GetById(id);
            return View(item);
        }
        /// <summary>
        /// 提交编辑信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="collection">客户端传回的集合</param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Edit(string id, ts_billmove entity)
        {
            using (TransactionScope transactionScope = new TransactionScope())
            {
                try
                {
                    //if (entity != null && ModelState.IsValid)
                    //{
                    string[] parentId = { entity.Id };
                    new ts_billmovedetailBLL().DeleteCollectionByParent(ref validationErrors, parentId);
                    string currentPerson = GetCurrentPerson();
                    //entity.CreateTime = DateTime.Now;
                    //entity.CreatePerson = currentPerson;

                    string returnValue = string.Empty;
                    if (m_BLL.Edit(ref validationErrors, entity))
                    {
                        //LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + "，入库表的信息的Id为" + entity.Id, "入库表"
                        //    );//写入日志 
                        //return Json(Suggestion.InsertSucceed);
                    }
                    else
                    {
                        if (validationErrors != null && validationErrors.Count > 0)
                        {
                            validationErrors.All(a =>
                            {
                                returnValue += a.ErrorMessage;
                                return true;
                            });
                        }
                        LogClassModels.WriteServiceLog(Suggestion.InsertFail + "，移库表的信息，" + returnValue, "移库表"
                            );//写入日志                      
                        return Json(Suggestion.InsertFail + returnValue); //提示插入失败
                    }

                    if (entity.GoodsDetail != null)
                    {
                        string[] rowsInf = entity.GoodsDetail.Split('^');

                        for (int i = 0; i < rowsInf.Length - 1; i++)
                        {
                            string aaad = rowsInf[i];
                            object arrayObj;
                            arrayObj = new Hashtable();
                            arrayObj = JSON.JsonDecode(rowsInf[i]);
                            Hashtable ht = (Hashtable)arrayObj;
                            Dictionary<string, string> dict = new Dictionary<string, string>();//Dictionary接受Json字符串
                            foreach (DictionaryEntry de in ht)
                            {
                                if (dict.ContainsKey(de.Key.ToString())) continue;//不能重复啊
                                dict.Add(de.Key.ToString(), de.Value == null ? "" : de.Value.ToString());
                            }

                            ts_billmovedetail billmovedetail = new ts_billmovedetail();
                            ts_billmovedetailBLL tbtb = new ts_billmovedetailBLL();
                            billmovedetail.Id = Result.GetNewId();
                            billmovedetail.c_type = "移库";
                            billmovedetail.i_no = entity.Id;
                            billmovedetail.i_num = i + 1;
                            billmovedetail.c_code = dict["c_code"].GetString();
                            billmovedetail.f_quant = Convert.ToDecimal(dict["f_quant"].GetString());
                            billmovedetail.f_price = StrToDecimal(dict["f_price"].GetString());
                            billmovedetail.f_amount = StrToDecimal(dict["f_quant"].GetString()) * StrToDecimal(dict["f_price"].GetString());
                            billmovedetail.c_comment = dict["c_comment"].GetString();

                            tbtb.Create(ref validationErrors, billmovedetail);

                        }
                        transactionScope.Complete();
                        LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + "，移库表的信息Id为" + entity.Id + "的商品信息", "移库商品表");//写入日志 
                        return Json(Suggestion.InsertSucceed);
                    }
                    transactionScope.Complete();
                    LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + "，移库表的信息Id为" + entity.Id, "移库表"
                           );//写入日志 
                    return Json(Suggestion.InsertSucceed);
                    //}
                }
                catch
                {
                    Transaction.Current.Rollback();
                }
            }

            return Json(Suggestion.InsertFail + "，请核对输入的数据的格式"); //提示输入的数据的格式不对                  
          
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>   
        [HttpPost]
        public ActionResult Delete(FormCollection collection)
        {
            string returnValue = string.Empty;
            string[] deleteId = collection["query"].GetString().Split(',');
            if (deleteId != null && deleteId.Length > 0)
            { 
                if (m_BLL.DeleteCollection(ref validationErrors, deleteId))
                {
                    LogClassModels.WriteServiceLog(Suggestion.DeleteSucceed + "，信息的Id为" + string.Join(",", deleteId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.DeleteFail + "，信息的Id为" + string.Join(",", deleteId)+ "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }
          
        IBLL.Its_billmoveBLL m_BLL;

        ValidationErrors validationErrors = new ValidationErrors();

        public ts_billmoveController()
            : this(new ts_billmoveBLL()) { }

        public ts_billmoveController(ts_billmoveBLL bll)
        {
            m_BLL = bll;
        }
        
    }
}


